Ext.BLANK_IMAGE_URL = 'js/ext-3.4.1/resources/images/default/s.gif';

Ext.onReady(function() {

    var loggedUser = Bible.loggedUser;

    /**
     * functioneaza in felul urmator:
     * daca detecteaza ca browserul are suport pt local storage, isi tine state-ul in local storage,
     * iar daca nu are local storage, nu foloseste cookie-uri, ci foloseste un hidden form
     *
     * Daca userul e logat, atunci ii dam ca parametru si un user id
     */
    Ext.state.Manager.setProvider(new Ext.ux.state.LocalProvider({
        userid: loggedUser ? loggedUser.email: 'app.bibliaonline.ro'
    }));

    Ext.QuickTips.init();

    Ext.apply(Ext.QuickTips.getQuickTip(), {
        dismissDelay: false,
        showDelay : 700
    });

    var //cookie = readCookie("style"),
//        selectedStyle = cookie ? cookie : getPreferredStyleSheet(),
        actions = Bible.getActions();

    //defaults = Ext.copyTo({}, actions, 'layout');
    //Ext.apply(Bible.defaults, defaults);
    if(actions.l){
        Bible.defaults.layout = actions.l;
    }
    if(actions.z){
        Bible.defaults.fontSize = actions.z;
    }

    console.debug('actions:', actions);

    // TODO chrome test combo width
//    new Bible.SearchGridPanel({
//        height: 500,
//        width: 600,
//        renderTo: Ext.getBody()
//    });
//    return;

    var desktop = new Bible.ReadContainer({
        id: 'desktop'
    });

    desktop.firstGrid.selectVerseAfterLoad(1); // TODO get from link
	
	var searchStore = new Bible.data.BibleSearchStore();	
    var resultTpl = new Ext.XTemplate(
		'<tpl for=".">',
			'<div class="x-combo-list-item" style="white-space: normal;">',
				'<span class="verse-nr">({verse})</span> {[this.rendererHighlight(values.text)]}',
			'</div>',
		'</tpl>',
		{
			rendererHighlight: function(text){
				return Bible.highlightTerms(text, searchStore).text;
			}
		}
	);
    var searchField = new Ext.form.ComboBox({
        store: searchStore,
        displayField:'text',
        typeAhead: false,
		emptyText: 'Caută în Biblie...',
        loadingText: 'Căutare...',
		queryDelay: 300,
        width: 170,
		listWidth: 400,
        pageSize: 10,
		minChars: 3,
		selectOnFocus: true,
		triggerClass:'x-form-search-trigger',
        tpl: resultTpl,
		initQuery : function(){
			//var split = searchField ? (searchField.split || (searchField.filterType && searchField.store.baseParams.type != 'text')) : false;
			var highlights = Ext.util.Terminology.createHighlightsTerms(this.getRawValue(), 2, true);
			this.store.searchField = {
				highlightsTerms: highlights.terms
			}
			Ext.form.ComboBox.prototype.initQuery.call(this);
		},
        onSelect: function(record){
			console.info('selected', record);
			desktop.setBibleGridPage(record, this.getRawValue());
			this.collapse();
        }/*,
		listeners: {
			select: function(combo, record, index){
				desktop.setBibleGridPage(record, this.getRawValue());
			}
		}*/
    });

	var viewPort = new Ext.Viewport({
        layout: 'fit',
        cls: 'font-size-' + Bible.defaults.fontSize,
		currentFontSize: 'font-size-' + Bible.defaults.fontSize,
        fontSizes: [11, 12, 14, 16, 18, 20, 22, 24, 28],
        items: new Ext.Panel({
            ref: 'panel',
            layout: 'border',
            border: false,
            tbar: new Ext.Toolbar({
                style: 'borderBottom: 0; borderLeft: 1px solid #99BBE8;',
                items: [
                    ' ',
                    {
                        ref: 'boxButton',
                        tooltip: 'O Coloană',
                        type: 'box',
                        iconCls: 'x-cols-single-icon',
                        pressed: Bible.defaults.layout == 'box',
                        enableToggle: true,
                        allowDepress: false,
                        toggleGroup:'cols-group',
                        scope: desktop,
                        toggleHandler: desktop.moveSecondView
                    },
                    {
                        ref: 'vboxButton',
                        tooltip: '2 Coloane (Vertical)',
                        type: 'vbox',
                        iconCls: 'x-cols-vbox-icon',
                        pressed: Bible.defaults.layout == 'vbox',
                        enableToggle: true,
                        allowDepress: false,
                        toggleGroup:'cols-group',
                        scope: desktop,
                        toggleHandler: desktop.moveSecondView
                    },
                    {
                        ref: 'hboxButton',
                        tooltip: '2 Coloane (Orizontal)',
                        type: 'hbox',
                        iconCls: 'x-cols-hbox-icon',
                        pressed: Bible.defaults.layout == 'hbox',
                        enableToggle: true,
                        allowDepress: false,
                        toggleGroup:'cols-group',
                        scope: desktop,
                        toggleHandler: desktop.moveSecondView
                    },
                    {
                        ref: 'tabsButton',
                        tooltip: 'Multiple File',
                        type: 'tabs',
                        pressed: Bible.defaults.layout == 'tabs',
                        enableToggle: true,
                        allowDepress: false,
                        toggleGroup:'cols-group',
                        iconCls: 'tabs',
                        scope: desktop,
                        toggleHandler: desktop.moveSecondView
                    },
                    '-',
                    {
                        tooltip: i18n.zoomOut,
                        iconCls: 'font-zoom-out-icon',
                        handler: function(){
                            viewPort.removeClass(viewPort.currentFontSize);
                            var i = viewPort.fontSizes.indexOf(parseInt(viewPort.currentFontSize.replace('font-size-', '')));
                            i = i > 0 ? i-1 : i;
                            viewPort.currentFontSize = 'font-size-' + viewPort.fontSizes[i];
                            viewPort.addClass(viewPort.currentFontSize);
                            Bible.setActions('z', viewPort.fontSizes[i]);
                        }
                    },
                    {
                        tooltip: i18n.zoomIn,
                        iconCls: 'font-zoom-in-icon',
                        handler: function(){
                            viewPort.removeClass(viewPort.currentFontSize);
                            var i = viewPort.fontSizes.indexOf(parseInt(viewPort.currentFontSize.replace('font-size-', '')));
                            i = i+1 < viewPort.fontSizes.length ? i+1 : i;
                            viewPort.currentFontSize = 'font-size-' + viewPort.fontSizes[i];
                            viewPort.addClass(viewPort.currentFontSize);
                            Bible.setActions('z', viewPort.fontSizes[i]);
                        }
                    },
					'-',
					searchField,
					{
						tooltip: i18n.advancedSearch,
                        iconCls: 'icon-find',
						handler: function(){
							viewPort.search.toggleCollapse(true);
						}
					},
                    '-',
                    {
                        tooltip: i18n.bookOverview,
                        //text: i18n.bookOverview,
						iconCls: 'icon-overview',
                        handler: function(){
                            if(!this.bookOverviewWin){
                                this.bookOverviewWin = new Ext.Window({
                                    title: i18n.bookOverview,
									iconCls: 'icon-overview',
//                                modal: true,
                                    maximizable: true,
                                    width: 700,
                                    height: 400,
                                    layout: 'fit',
                                    border: false,
                                    closeAction: 'hide',
                                    items: new Bible.grid.BookThemesGridPanel()
                                });
                            }

                            this.bookOverviewWin.show();
                        }
                    },
                    '->',
//                    {
//                        xtype: 'combo',
//                        width: 100,
//                        mode: 'local',
//                        value: selectedStyle ? selectedStyle : 'blue',
//                        editable: false,
//                        allowBlank: false,
//                        selectOnFocus: true,
//                        lastQuery: '',
//                        lazyInit: false,
//                        //lazyRender: false,
//                        forceSelection: true,
//                        typeAhead: true,
//                        triggerAction: 'all',
//                        displayField:'name',
//                        valueField: 'id',
//                        store: new Ext.data.ArrayStore({
//                            fields: ['id', 'name'],
//                            idIndex: 0,
//                            data : [['blue', 'Blue Theme'],['gray', 'Gray Theme']]
//                        }),
//                        listeners: {
//                            select: function(combo, record, index){
//                                var name = record.get('id');
//                                console.debug('change theme to: ', name);
//                                setActiveStyleSheet(name);
//                            }
//                        }
//                    },
                    {
                        text: i18n.preferences,
                        iconCls: 'preferences',
//                        hidden: !Bible.loggedUser,
                        handler: function(){
                            Bible.showPreferencesWin();
                        }
                    },
                    {
                        xtype: 'tbseparator'
//                        hidden: !Bible.loggedUser
                    },
                    {
                        tooltip: i18n.info,
                        iconCls: 'icon-docs',
                        handler: function(){
                            Bible.showDocs();
                        }
                    },
                    '-',
                    {
                        text: !loggedUser ? i18n.login : i18n.logout,
						iconCls: 'login',
                        handler: function(){
                            if(!Bible.loggedUser){
                                Bible.doLogin();
                            } else {
                                Bible.doLogout();
                            }
                        }
                    },
                    {
                        xtype: 'tbseparator',
                        hidden: !!loggedUser
                    },
                    {
                        text: i18n.register,
                        hidden: !!loggedUser,
						iconCls: 'user_add',
                        handler: function(){
                            Bible.showRegisterForm();
                        }
                    }
                ]
            }),

            items:[{
                ref: '../search',
                region: 'west',
                title: i18n.search,
                xtype: 'searchgridpanel',
                activeReader: desktop,
                split: true,
                width: 325,
                minSize: 200,
                maxSize: 400,
                collapsed: true,
                collapseMode:'mini',
                collapsible: true
            },
            {
                region: 'center',
                xtype: 'container',
                layout: 'fit',
                border: false,
                items: desktop
            }],

             bbar: new Ext.Toolbar({
                style: 'borderTop: 0; borderLeft: 1px solid #99BBE8;',
                items: [
                    {
                        xtype: 'tbtext',
                        text: loggedUser ? loggedUser.email : ''
                    },
                    '->',
                    {
                        id: 'app-name-version',
                        xtype: 'tbtext',
                        text: '&copy; Biblia pentru Studiu '+ Bible.version + ' <span class="author">(autor Matei Nicolae)</span>'
                    }
                ]
            })
        })
    });

    Bible.viewPort = viewPort;

    if(actions.action == 'resetpass'){
        Bible.showResetPassWin(true);
        Bible.removeAction('action');
    }
});
